﻿using CCWin;
using ERP_SaaS_WinForm.登录.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.Http;

using System.Threading.Tasks;
using System.Windows.Forms;




namespace ERP_SaaS_WinForm.登录
{
    public partial class ShowProducts : CCSkinMain
    {
        public ShowProducts()
        {

            InitializeComponent();
            cmpagesize.SelectedIndex = 0; // 默认选择每页显示15条
            LoadPageData(); // 重新加载数据
            this.Load += ShowProducts_Load;
        }
        public HttpClient client = new HttpClient();
        private async void ShowProducts_Load(object sender, EventArgs e)
        {
            ShowType();
        }


        /// 动态获取下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public async void ShowType()
        {
            var response = await client.GetAsync($"http://10.223.8.3:8077/api/SelectAll/ShowProductTypes");
            // 确保响应成功
            if (response.IsSuccessStatusCode)
            {
                response.EnsureSuccessStatusCode();//确保响应成功

                string json = await response.Content.ReadAsStringAsync();//字符串形式的json数据

                ApiResponse<ProductTypes> apiResponse = JsonConvert.DeserializeObject<ApiResponse<ProductTypes>>(json);//字符串json数据反序列化成ApiResponse对象

                // 步骤3: 提取data数据
                var listData = apiResponse.data;
                List<ProductTypes> data = listData;

                // 绑定到ComboBox
                // 注意：如果当前不在UI线程，需要切换到UI线程
                if (cbxtype.InvokeRequired)
                {
                    cbxtype.Invoke(new Action(() =>
                    {
                        cbxtype.DataSource = data;
                        cbxtype.ValueMember = "ProductTypeName";   // 设置显示成员
                        cbxtype.DisplayMember = "ProductTypeName";    // 设置值成员
                        cbxtype.SelectedIndex = -1;
                    }));
                }
                else
                {
                    cbxtype.DataSource = data;
                    cbxtype.ValueMember = "ProductTypeName";
                    cbxtype.DisplayMember = "ProductTypeName";
                    cbxtype.SelectedIndex = -1;
                }
            }

        }
        public async void ShowAttributes()
        {
            var response = await client.GetAsync($"http://10.223.8.3:8077/api/SelectAll/ShowProductAttributes");
        }

        private int currentPage = 1; // 当前页码
        private int pageSize = 999; // 默认每页行数

        private int totalPages; // 总页数
        private string apiUrl = "http://10.223.8.3:8077/api/Product/ShowProducts"; // API地址




        private void dtnget_Click(object sender, EventArgs e)
        {
            LoadPageData();
        }
        /// <summary>
        /// 点击第一页按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtfirst_Click(object sender, EventArgs e)
        {
            currentPage = 1;
            LoadPageData();
        }
        /// <summary>
        /// 点击最后一页按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void txtlast_Click(object sender, EventArgs e)
        {
            currentPage = totalPages;
            LoadPageData();
        }

        // 分页按钮点击事件
        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (currentPage > 1)
            {
                currentPage--;
                LoadPageData();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (currentPage < totalPages)
            {
                currentPage++;
                LoadPageData();
            }
        }

        private void cmpagesize_SelectedIndexChanged(object sender, EventArgs e)
        {

            LoadPageData();
        }

        /// <summary>
        /// 分页显示
        /// </summary>
        /// <returns></returns>
        private async void LoadPageData()
        {
            try
            {
                // 构建API请求（含分页参数）
                string requestUrl = $"{apiUrl}?currentpage={currentPage}&pagesize={cmpagesize.Text}&productname={txtname.Text}&productype={cbxtype.SelectedValue}&producState={txtstate.SelectedValue}";
                HttpResponseMessage response = await client.GetAsync(requestUrl);
                string json = await response.Content.ReadAsStringAsync();

                // 反序列化为ApiPaging<T>（假设T是List<YourModel>）
                var apiPaging = JsonConvert.DeserializeObject<ApiPaging<List<Products>>>(json);
                // 绑定数据到DataGridView
                PagedataView.DataSource = apiPaging.data;
                // 更新分页信息显示
                lblMassage.Text = $"第{apiPaging.currentpage}页/共{apiPaging.totalpages}页 (总记录: {apiPaging.totalcount})";
                totalPages = apiPaging.totalpages;

            }
            catch (Exception ex)
            {
                MessageBox.Show($"API调用失败: {ex.Message}");
            }

        }
        private string apiUrlid = "http://10.223.8.3:8077/api/Logines/CheckEnf"; // API地址
        public async void ShowMessage(int id)
        {
            var responva = await client.GetAsync($"{apiUrlid}?id={id}");
            responva.EnsureSuccessStatusCode();//确保响应成功

            string json = await responva.Content.ReadAsStringAsync();//字符串形式的json数据

            ApiResponse<Products> apiResponse = JsonConvert.DeserializeObject<ApiResponse<Products>>(json);//字符串json数据反序列化成ApiResponse对象

            // 步骤3: 提取data数据
            var listData = apiResponse.data;
          
            if (listData.FirstOrDefault().Isdel == true)
            {
                // 打开编辑窗体
                var procurementForm = new ERP_SaaS_WinForm.登录.ShowProductInspections();
                procurementForm.Show();
            }
            else
            {
                MessageBox.Show($"当前库存数量不够");
            }
        }




        //按钮点击事件1
        private void PagedataView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {



            // 确保点击的是“编辑”或“删除”按钮列
            if (PagedataView.Columns[e.ColumnIndex] is DataGridViewButtonColumn)
            {
                string columnName = PagedataView.Columns[e.ColumnIndex].Name;

                // 获取当前行的数据
                int rowIndex = e.RowIndex;
                DataGridViewRow row = PagedataView.Rows[rowIndex];

                // 处理编辑操作
                if (columnName == "editbtn")
                {
                    //确认是否编辑
                    DialogResult result = MessageBox.Show("确定要检查该记录吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {

                        ShowMessage(Convert.ToInt32(row.Cells["Productions_Id"].Value));
          
                    }
                }
            }
        }
    }
}

